﻿using System.Security.Cryptography;

namespace PhiStore.Security
{
    internal class EncryptionSettings
    {
        private static EncryptionSettings instance = null;

        private RSAParameters publicKey;
        private RSAParameters privateKey;
        private RSACryptoServiceProvider rsa;

        private object mutex = new object();

        private EncryptionSettings()
        {
            LoadSettings();
        }

        public static EncryptionSettings Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new EncryptionSettings();
                }
                return instance;
            }
        }

        public RSAParameters PrivateKey
        {
            get {
                lock (mutex)
                {
                    return privateKey;
                }
            }
        }

        public RSAParameters PublicKey
        {
            get {
                lock (mutex)
                {
                    return publicKey;
                }
            }
        }

        #region Settings stuff
       
        
        private void LoadSettings()
        {
            try
            {
                string parameters = SettingsManager.Instance.Read<string>("RSA");
                rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(parameters);
               
                publicKey = rsa.ExportParameters(false);
                privateKey = rsa.ExportParameters(true);
            }
            catch
            {
                rsa = new RSACryptoServiceProvider(4096);
                privateKey = rsa.ExportParameters(true);
                publicKey = rsa.ExportParameters(false);
                SaveSettings();
            }
        }
        private void SaveSettings()
        {
            string parameters = rsa.ToXmlString(true);

            SettingsManager.Instance.Add("RSA", parameters);
        }
        #endregion
    }
}
